package com.zyx.concurrentdemo.mytest.c04;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/13 13:19
 */
public class ThreadSafeDemo {

    private static final int LOOP_NUMBER = 1000;
    private static final int THREAD_NUMBER = 2;

    public static void main(String[] args) {
        // ThreadUnsafe test = new ThreadUnsafe();
        // ThreadSafe test = new ThreadSafe();
        ThreadSafeSubClass test = new ThreadSafeSubClass();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> {
                test.method1(LOOP_NUMBER);
            }, "Thread" + i).start();
        }
    }
}

class ThreadUnsafe {
    List<String> list = new ArrayList<>();

    public void method1(int loop) {
        for (int i = 0; i < loop; i++) {
            method2();
            method3();
        }
    }

    public void method2() {
        list.add("1");
    }

    public void method3() {
        list.remove(0);
    }

}

class ThreadSafe {

    public void method1(int loop) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < loop; i++) {
            method2(list);
            method3(list);
        }
    }

    private void method2(List<String> list) {
        list.add("1");
    }

    private void method3(List<String> list) {
        list.remove(0);
    }

}

class ThreadSafeSubClass extends ThreadSafe {

    // @Override
    public void method3(List<String> list) {
        // 重写父类的方法可能会导致线程不安全
        // 注意体会Java面向对象 开闭原则中的【闭】原则
        new Thread(() -> {
            list.remove(0);
        }).start();
    }

}



















